package breakthrough;

import game.GameState;

import java.util.ArrayList;
import java.util.Collections;

public class BreakthroughUtil {

	/**
     * Generates a list of all legal moves for the state's active player.
     * 
     * @param state
     *            the game state to be examined
     * @return an ArrayList of legal moves for the given state
     */
    public static final ArrayList<BreakthroughMove> getLegalMoves(final BreakthroughState state)
    {
        // TODO Optimize, optimize, optimize.

        // smithre5: Using 4.5 here (or 75%) since most situations will never
        // actually reach b_max. Tests on 1,000 round tournaments only reached
        // 65-70% of b_max. This gives a slight performance boost.
        ArrayList<BreakthroughMove> moves = new ArrayList<BreakthroughMove>((int)(4.5f * BreakthroughState.N));

        // Initial values for sanity checks in debugging.
        char pSymbol = '?';
        int pDelta = 0;

        if (state.getWho() == GameState.Who.HOME) {
            pSymbol = BreakthroughState.homeSym;
            pDelta = +1;
        }
        else {
            pSymbol = BreakthroughState.awaySym;
            pDelta = -1;
        }

        for (int row = 0; row < BreakthroughState.N; ++row) {
            for (int col = 0; col < BreakthroughState.N; ++col) {
                // skip non-player pieces
                if (state.board[row][col] != pSymbol) {
                    continue;
                }

                int nextRow = row + pDelta;
                
                // can move piece?
                if (nextRow >= 0 && nextRow < BreakthroughState.N) {
                	
                	int leftCol = col - 1;
                    int rightCol = col + 1;
                	
                    char[] rowContents = state.board[nextRow];

                    // can move forward?
                    if (rowContents[col] == BreakthroughState.emptySym) {
                        moves.add(new BreakthroughMove(row, col, nextRow, col));
                    }

                    // can move left?
                    if (leftCol >= 0 && rowContents[leftCol] != pSymbol) {
                        moves.add(new BreakthroughMove(row, col, nextRow, leftCol));
                    }

                    // can move right?
                    if (rightCol < BreakthroughState.N && rowContents[rightCol] != pSymbol) {
                        moves.add(new BreakthroughMove(row, col, nextRow, rightCol));
                    }
                }
            }
        }
        // Random move ordering.
        Collections.shuffle(moves);

        return moves;
    }
	
}
